package com.oc.mba.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.oc.mba.controller.BackendController;
import com.oc.mba.dao.BaseDAOHibernate;
import com.oc.mba.dao.OcOrderDAO;
import com.oc.mba.entity.OcOrder;
import com.oc.mba.util.CommLog;

@Repository
public class OcOrderDAOImpl extends BaseDAOHibernate implements OcOrderDAO {

	private static final CommLog logger = new CommLog(OcOrderDAOImpl.class);
	
	@Override
	public void save(OcOrder order) {
		getHibernateTemplate().save(order);
	}

	@Override
	public void payOrder(String orderID, String cost) {
		List<OcOrder> orders = findByProperty("orderId", orderID);
		if(orders!=null && orders.size() > 0) {
			OcOrder order = orders.get(0);
			order.setOrderCost(Double.valueOf(cost));
			order.setFinished((short)1);
			getHibernateTemplate().saveOrUpdate(order);
		}
		else {
			logger.error("Can not Order. OrderId=" + orderID + ", cost=" + cost);
		}
	}
	
	public List<OcOrder> findByProperty(String propertyName, Object value) {
		logger.debug("finding OcOrder instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from OcOrder as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		}
		catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}

	@Override
	public OcOrder findOrder(String orderID) {
		List<OcOrder> orders = findByProperty("orderId", orderID);
		if(orders!=null && orders.size() > 0) {
			OcOrder order = orders.get(0);
			return order;
		}
		else {
			logger.error("Can not Order. OrderId=" + orderID);
			return null;
		}
	}

	@Override
	public OcOrder findById(Integer orderID) {
		OcOrder ocOrder = getHibernateTemplate().get(OcOrder.class, orderID);
		return ocOrder;
//		List<OcOrder> orders = findByProperty("id", orderID);
//		if(orders!=null && orders.size() > 0) {
//			OcOrder order = orders.get(0);
//			return order;
//		}
//		else {
//			logger.error("Can not Order. OrderId=" + orderID);
//			return null;
//		}
	}

	@Override
	public void payOrder(OcOrder order, String cost) {
		order.setOrderCost(Double.valueOf(cost));
		order.setFinished((short)1);
		getHibernateTemplate().saveOrUpdate(order);
	}

}
